﻿layui.use(['table', 'dropdown', 'layer', 'form'], function () {
    var table = layui.table;
    var dropdown = layui.dropdown;
    var layer = layui.layer;
    var form = layui.form;
    var laypage = layui.laypage;
    window.DeviceTan = function DeviceTan() {
        layer.open({
            type: 1, //page 层类型
            area: ['800px', '400px'],
            title: '新增设备',
            shade: 0.6, //遮罩透明度
            shadeClose: true, //点击遮罩区域，关闭弹层
            maxmin: true, //允许全屏最小化
            anim: 0, //0-6 的动画形式，- 1 不开启
            content: `
                                  <div style="padding: 32px;">
                                           <form class="layui-form layui-form-pane" action="">
                                            <div class="layui-form-item">
                                             <div class="layui-inline">
                                                       <label class="layui-form-label">设备编号:</label>
                                               <div class="layui-input-block">
                                                         <input type="text" id="deviceNo1" lay-verify="required" placeholder="请输入"      autocomplete="off"  class="layui-input">

                                               </div>
                                             </div>
                                             <div class="layui-inline">
                                                       <label class="layui-form-label">设备名称:</label>
                                               <div class="layui-input-inline">
                                                        <input type="text" id="deviceName1" lay-verify="required" placeholder="请输入"   autocomplete="off"  class="layui-input">
                                               </div>
                                             </div>
                                           </div>
                                             <div class="layui-form-item">
                                             <div class="layui-inline">
                                                       <label class="layui-form-label">授权标识符:</label>
                                               <div class="layui-input-block">
                                                           <input type="text" id="deviceAccreNo" lay-verify="required" placeholder="请输入"     autocomplete="off"  class="layui-input">
                                               </div>
                                              </div>
                                             <div class="layui-inline">
                                                               <label class="layui-form-label">是否授权:</label>
                                               <div class="layui-input-inline">
                                                              <input type="checkbox" name="isAccre" value=false title="授权">
                                               </div>
                                             </div>
                                           </div>
                                             <div class="layui-form-item">
                                             <div class="layui-inline">
                                                       <label class="layui-form-label">状态:</label>
                                               <div class="layui-input-block">
                                                         <select id="deviceStatus" lay-filter="aihao">
                                                     <option value="0">全部</option>
                                                     <option value="1">闲置</option>
                                                     <option value="2">运行</option>
                                                 </select>
                                               </div>
                                             </div>
                                             <div class="layui-inline">
                                                       <label class="layui-form-label">备注:</label>
                                               <div class="layui-input-inline">
                                                          <input type="text" id="deviceRemarks" lay-verify="required" placeholder="请输入"   autocomplete="off"  class="layui-input" />

                                               </div>
                                             </div>
                                           </div>
                                   </div>
                                   <div class="layui-form-item">
                                             <button class="layui-btn" lay-submit lay-filter="demo2" onclick="DeviceAdd()">确认</button>
                                     <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                                   </div>
                                 </form>
                                   </div>`

        });

        form.render()
    }

    window.FanUpdate = function FanUpdate(deviceId) {
        var token = localStorage.getItem("token")
        var model = JSON.stringify({
            deviceId: deviceId
        })
        $.ajax({
            url: '../Device/DeviceFanDo',
            data: { model: model, token: token },
            type: 'post',
            success: function (res) {
                var res = JSON.parse(res)
                console.log(res)
                $.each(res, function () {
                    $("#deviceId").val(this.deviceId)
                    $("#deviceNo1").val(this.deviceNo)
                    $("#deviceName1").val(this.deviceName)
                    $("#deviceAccreNo").val(this.deviceAccreNo)
                    $("#isAccre").val(this.isAccre)
                    $("#deviceStatus").val(this.deviceStatus)
                    $("#deviceRemarks").val(this.deviceRemarks)
                    // 设置下拉框默认选择
                    var deviceStatus = this.deviceStatus;
                    $("#deviceStatus").val(deviceStatus);
                    layui.form.render('select'); // 重新渲染select表单元素
                    // 设置复选框默认选择
                    var isAccre = this.isAccre;
                    if (isAccre === false) {
                        $('#isAccre').prop('checked', true);
                    } else {
                        $('#isAccre').prop('checked', false);
                    }
                    form.render('checkbox'); // 重新渲染checkbox表单元素
                })
            }
        })
        layer.open({
            type: 1, //page 层类型
            area: ['800px', '400px'],
            title: '修改设备',
            shade: 0.6, //遮罩透明度
            shadeClose: true, //点击遮罩区域，关闭弹层
            maxmin: true, //允许全屏最小化
            anim: 0, //0-6 的动画形式，- 1 不开启
            content: `
                                          <div style="padding: 32px;">
                                                   <form class="layui-form layui-form-pane" action="">
                                                    <div class="layui-form-item">
                                                     <div class="layui-inline">
                                                               <label class="layui-form-label">设备编号:</label>
                                                       <div class="layui-input-block">
                                                                 <input type="text" id="deviceNo1" lay-verify="required" placeholder="请输入"      autocomplete="off"  class="layui-input">

                                                       </div>
                                                     </div>
                                                     <div class="layui-inline">
                                                               <label class="layui-form-label">设备名称:</label>
                                                       <div class="layui-input-inline">
                                                                <input type="text" id="deviceName1" lay-verify="required" placeholder="请输入"   autocomplete="off"  class="layui-input">
                                                       </div>
                                                     </div>
                                                   </div>
                                                     <div class="layui-form-item">
                                                     <div class="layui-inline">
                                                               <label class="layui-form-label">授权标识符:</label>
                                                       <div class="layui-input-block">
                                                                   <input type="text" id="deviceAccreNo" lay-verify="required" placeholder="请输入"     autocomplete="off"  class="layui-input">
                                                       </div>
                                                      </div>
                                                     <div class="layui-inline">
                                                                       <label class="layui-form-label">是否授权:</label>
                                                       <div class="layui-input-inline">
                                                                      <input type="checkbox" id="isAccre" name="isAccre" value="false" title="授权">
                                                       </div>
                                                     </div>
                                                   </div>
                                                     <div class="layui-form-item">
                                                     <div class="layui-inline">
                                                               <label class="layui-form-label">状态:</label>
                                                       <div class="layui-input-block">
                                                                         <select id="deviceStatus" name="deviceStatus" lay-filter="aihao">
                                                             <option value="0">全部</option>
                                                             <option value="1">闲置</option>
                                                             <option value="2">运行</option>
                                                         </select>
                                                       </div>
                                                     </div>
                                                     <div class="layui-inline">
                                                               <label class="layui-form-label">备注:</label>
                                                       <div class="layui-input-inline">
                                                                  <input type="text" id="deviceRemarks" lay-verify="required" placeholder="请输入"   autocomplete="off"  class="layui-input" />

                                                       </div>
                                                     </div>
                                                   </div>
                                           </div>
                                           <div class="layui-form-item">
                                                             <button class="layui-btn" lay-submit lay-filter="demo2" onclick="Update()">确认</button>
                                             <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                                           </div>
                                         </form>
                                           </div>`

        });
        form.render()
        window.Update = function Update() {
            deviceAccreNo = $("#deviceAccreNo").val()
            deviceRemarks = $("#deviceRemarks").val()
            deviceNo = $("#deviceNo1").val()
            deviceName = $("#deviceName1").val()
            deviceStatus = $("#deviceStatus").val()
            var models = JSON.stringify({
                "deviceId": parseInt((deviceId)),
                "deviceAccreNo": deviceAccreNo,
                "deviceRemarks": deviceRemarks,
                "deviceNo": deviceNo,
                "deviceName": deviceName,
                "deviceStatus": parseInt(deviceStatus),
                "isAccre": false,
            })
            console.log(models)
            var token = localStorage.getItem("token")
            $.ajax({
                url: '../Device/DeviceupdateDo',
                type: 'post',
                data: { models: models, token: token },
                //contentType: 'application/json',
                success: function (res) {
                    console.log(res)
                    var res = JSON.parse(res)
                    if (res > 0) {
                        alert("修改成功")
                        window.location.href = '/Device/Device'
                    }
                    else {
                        alert("修改失败")
                    }

                }
            })
        }
    }

    window.Show = function Show() {
        var token = localStorage.getItem("token")
        var model = JSON.stringify({
            deviceNo: $("#deviceNo").val(),
            deviceName: $("#deviceName").val(),
        })

        $.ajax({
            url: '../Device/DeviceDo',
            type: 'post',
            //contentType: 'application/json',
            data: { model: model, token: token },
            success: function (res) {
                res = JSON.parse(res);

                // 更新总记录数
                totalCount = res.totalCount;
                //总页数
                sum = res.totalPage;
                console.log(res)
                // 处理数据并渲染表格
                var cols = [
                    [
                        { field: 'deviceId', type: 'checkbox', fixed: 'left' },
                        { field: 'deviceId', title: '设备ID', width: 80 },
                        { field: 'deviceNo', title: '设备编号', width: 120 },
                        { field: 'deviceName', title: '设备名称', width: 120 },
                        {
                            field: 'isAccre', title: '是否授权', width: 80, templet: function (d) {
                                return d.isAccre === 0 ? '是' : '否';
                            }
                        },
                        { field: 'deviceAccreNo', title: '设备认证编号', width: 120 },
                        {
                            field: '设备状态', title: '设备状态', width: 80, templet: function (d) {
                                return d.deviceStatus === 1 ? '闲置' : '运行';
                            }
                        },
                        { field: 'deviceRemarks', title: '设备备注', width: 200 },
                        {
                            fixed: 'right', title: '操作', width: 150, templet: function (d) {
                                return '<a href="#" class="layui-btn layui-btn-xs layui-btn-primary" onclick="FanUpdate(' + d.deviceId + ')">编辑</a>' +
                                    '<a href="#" class="layui-btn layui-btn-xs layui-btn-danger" onclick="IsDel(' + d.deviceId + ')">删除</a>';
                            }
                        }
                    ]
                ];
                table.render({
                    elem: '#test',
                    data: res,
                    cols: cols,
                    page: true,
                    limits: [5, 10, 15, 20],
                    limit: 5,//设置每页显示的条数。
                });
            },
        });
    }

    // 可以通过这个函数获取总条数
    function getTotalCount() {
        return totalCount;
    }
    window.IsDel = function IsDel(deviceId) {
        var token = localStorage.getItem("token")
        var model = JSON.stringify({
            deviceId: deviceId
        })
        layer.confirm("确认删除吗", function () {
            $.ajax({
                url: '../Device/IsDelDo',
                data: { model: model, token: token },
                type: 'post',
                success: function (res) {
                    console.log(res);
                    var res = JSON.parse(res);
                    if (res > 0) {
                        layer.msg("删除成功", {icon: 1});
                        Show();
                    } else {
                        layer.msg("删除失败", { icon: 2 });
                    }
                }
            });
        });
    }

    $(function () {
        Show()
    })
    window.DeviceAdd = function DeviceAdd() {
        var isAccre = document.getElementsByName("isAccre")[0].checked
        if (isAccre == null) {
            isAccre = true
        }
        deviceAccreNo = $("#deviceAccreNo").val()
        deviceRemarks = $("#deviceRemarks").val()
        deviceNo = $("#deviceNo1").val()
        deviceName = $("#deviceName1").val()
        deviceStatus = $("#deviceStatus").val()
        var model = JSON.stringify({
            "deviceAccreNo": deviceAccreNo,
            "deviceRemarks": deviceRemarks,
            "deviceNo": deviceNo,
            "deviceName": deviceName,
            "deviceStatus": parseInt(deviceStatus),
            "isAccre": false,
        })
        console.log(model)
        var token = localStorage.getItem("token")
        $.ajax({
            url: '../Device/DeviceAddDo',
            type: 'post',
            data: { model: model, token: token },
            //contentType: 'application/json',
            success: function (res) {
                console.log(res)
                var res = JSON.parse(res)
                if (res > 0) {
                    alert("添加成功")
                    window.location.href = '/Device/Device'
                }
                else {
                    alert("添加失败")
                }

            }
        })
    }

    window.Output = function Output() {
        var data = [];

        //直接获取表格正文数据并添加到data数组，跳过表头（thead）获取
        $('table.layui-table tbody tr').each(function () {
            var rowData = [];
            $(this).find('td').each(function () {
                rowData.push($(this).text());
            });
            data.push(rowData);
        });

        //将数据转换为Worksheet对象
        var worksheet = XLSX.utils.aoa_to_sheet(data);

        //创建一个新的Workbook对象，并将Worksheet添加进去
        var workbook = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(workbook, worksheet, "Sheet1");

        //将Workbook对象转换为二进制数据
        var wbout = XLSX.write(workbook, { bookType: 'xlsx', type: 'binary' });

        //将二进制数据转换为Blob对象
        function s2ab(s) {
            var buf = new ArrayBuffer(s.length);
            var view = new Uint8Array(buf);
            for (var i = 0; i < s.length; i++) {
                view[i] = s.charCodeAt(i) & 0xff;
            }
            return new Blob([buf], { type: 'application/octet-stream' });
        }
        var blob = s2ab(wbout);

        //创建一个下载链接并触发点击事件来下载文件
        var url = URL.createObjectURL(blob);
        var link = document.createElement('a');
        link.href = url;
        link.download = '设备Device.xlsx';
        link.click();

        //释放URL对象
        URL.revokeObjectURL(url);
    }

     window.IsdelAll = function IsdelAll() {
         var checkStatus = table.checkStatus('test');
         var checkedData = checkStatus.data;
         var deviceIds = [];
         for (var i = 0; i < checkedData.length; i++) {
             deviceIds.push(checkedData[i].deviceId);
         }
         var model = JSON.stringify({
             ins: deviceIds
         });
        console.log(model);
         var token = localStorage.getItem("token")
         if (deviceIds == 0) {
             layer.msg("至少选择一条数据", { icon: 2 })
             return;
         }
         layer.confirm("确认删除吗", function () {
            $.ajax({
                url: '../Device/DeviceIsdelAllDo',
                data: { model: model, token: token },
                type: 'post',
                success: function (res) {
                    console.log(res);
                    var res = JSON.parse(res)
                    if (res > 0) {
                        layer.msg("批量删除成功", { icon: 1 })
                        Show();
                    }
                    else {
                        layer.msg("批量删除失败", { icon: 2 })
                    }
                }
            })
        })
    }

     window.FanUpdateAll = function FanUpdateAll() {
         var token = localStorage.getItem("token")
         var checkStatus = table.checkStatus('test');
         var checkedData = checkStatus.data;
         var deviceIds = [];
         for (var i = 0; i < checkedData.length; i++) {
             deviceIds.push(checkedData[i].deviceId);
         }
        var model = JSON.stringify({
            deviceId: deviceIds[0]
        })
        $.ajax({
            url: '../Device/DeviceFanDo',
            data: { model: model, token: token },
            type: 'post',
            success: function (res) {
                var res = JSON.parse(res)
                console.log(res)
                $.each(res, function () {
                    $("#deviceId").val(this.deviceId)
                    $("#deviceNo1").val(this.deviceNo)
                    $("#deviceName1").val(this.deviceName)
                    $("#deviceAccreNo").val(this.deviceAccreNo)
                    $("#isAccre").val(this.isAccre)
                    $("#deviceStatus").val(this.deviceStatus)
                    $("#deviceRemarks").val(this.deviceRemarks)
                    // 设置下拉框默认选择
                    var deviceStatus = this.deviceStatus;
                    $("#deviceStatus").val(deviceStatus);
                    layui.form.render('select'); // 重新渲染select表单元素
                    // 设置复选框默认选择
                    var isAccre = this.isAccre;
                    if (isAccre === false) {
                        $('#isAccre').prop('checked', true);
                    } else {
                        $('#isAccre').prop('checked', false);
                    }
                    form.render('checkbox'); // 重新渲染checkbox表单元素
                })
            }
        })
        layer.open({
            type: 1, //page 层类型
            area: ['800px', '400px'],
            title: '修改设备',
            shade: 0.6, //遮罩透明度
            shadeClose: true, //点击遮罩区域，关闭弹层
            maxmin: true, //允许全屏最小化
            anim: 0, //0-6 的动画形式，- 1 不开启
            content: `
                                          <div style="padding: 32px;">
                                                   <form class="layui-form layui-form-pane" action="">
                                                    <div class="layui-form-item">
                                                     <div class="layui-inline">
                                                               <label class="layui-form-label">设备编号:</label>
                                                       <div class="layui-input-block">
                                                                 <input type="text" id="deviceNo1" lay-verify="required" placeholder="请输入"      autocomplete="off"  class="layui-input">

                                                       </div>
                                                     </div>
                                                     <div class="layui-inline">
                                                               <label class="layui-form-label">设备名称:</label>
                                                       <div class="layui-input-inline">
                                                                <input type="text" id="deviceName1" lay-verify="required" placeholder="请输入"   autocomplete="off"  class="layui-input">
                                                       </div>
                                                     </div>
                                                   </div>
                                                     <div class="layui-form-item">
                                                     <div class="layui-inline">
                                                               <label class="layui-form-label">授权标识符:</label>
                                                       <div class="layui-input-block">
                                                                   <input type="text" id="deviceAccreNo" lay-verify="required" placeholder="请输入"     autocomplete="off"  class="layui-input">
                                                       </div>
                                                      </div>
                                                     <div class="layui-inline">
                                                                       <label class="layui-form-label">是否授权:</label>
                                                       <div class="layui-input-inline">
                                                                      <input type="checkbox" id="isAccre" name="isAccre" value="false" title="授权">
                                                       </div>
                                                     </div>
                                                   </div>
                                                     <div class="layui-form-item">
                                                     <div class="layui-inline">
                                                               <label class="layui-form-label">状态:</label>
                                                       <div class="layui-input-block">
                                                                         <select id="deviceStatus" name="deviceStatus" lay-filter="aihao">
                                                             <option value="0">全部</option>
                                                             <option value="1">闲置</option>
                                                             <option value="2">运行</option>
                                                         </select>
                                                       </div>
                                                     </div>
                                                     <div class="layui-inline">
                                                               <label class="layui-form-label">备注:</label>
                                                       <div class="layui-input-inline">
                                                                  <input type="text" id="deviceRemarks" lay-verify="required" placeholder="请输入"   autocomplete="off"  class="layui-input" />

                                                       </div>
                                                     </div>
                                                   </div>
                                           </div>
                                           <div class="layui-form-item">
                                                             <button class="layui-btn" lay-submit lay-filter="demo2" onclick="UpdateAll()">确认</button>
                                             <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                                           </div>
                                         </form>
                                           </div>`

        });
        form.render()
        window.UpdateAll = function UpdateAll() {
            deviceAccreNo = $("#deviceAccreNo").val()
            deviceRemarks = $("#deviceRemarks").val()
            deviceNo = $("#deviceNo1").val()
            deviceName = $("#deviceName1").val()
            deviceStatus = $("#deviceStatus").val()
            var models = JSON.stringify({
                "deviceId": parseInt((deviceIds[0])),
                "deviceAccreNo": deviceAccreNo,
                "deviceRemarks": deviceRemarks,
                "deviceNo": deviceNo,
                "deviceName": deviceName,
                "deviceStatus": parseInt(deviceStatus),
                "isAccre": false,
                "isDelete":false
            })
            console.log(models)
            var token = localStorage.getItem("token")
            $.ajax({
                url: '../Device/DeviceupdateDo',
                type: 'post',
                data: { models: models, token: token },
                //contentType: 'application/json',
                success: function (res) {
                    console.log(res)
                    var res = JSON.parse(res)
                    if (res > 0) {
                        alert("修改成功")
                        window.location.href = '/Device/Device'
                    }
                    else {
                        alert("修改失败")
                    }

                }
            })
        }
    }
});